<template>
  <div>
    <vxe-button
      style="margin-bottom: 20px"
      @click="showUserAdd"
      status="primary"
      icon="vxe-icon-add"
    >
      添加用户
    </vxe-button>
    <vxe-button
      status="primary"
      icon="vxe-icon-download"
      @click="generateReport"
      >导出PDF</vxe-button
    >
    <vxe-table
      border
      ref="xTable1"
      class="sortable-row-demo"
      :row-config="{ useKey: true }"
      :scroll-y="{ enabled: false }"
      :data="demo1.tableData"
      :column-config="{ resizable: true }"
      :edit-config="{ trigger: 'click', mode: 'row' }"
      @edit-closed="Editconfig"
    >
      >
      <vxe-column width="60">
        <template #default>
          <span class="drag-btn">
            <i class="vxe-icon-edit"></i>
          </span>
        </template>
        <template #header>
          <vxe-tooltip
            v-model="demo1.showHelpTip"
            content="按住后可以上下拖动排序！"
            enterable
          >
            <i
              class="vxe-icon-question-circle-fill"
              @click="demo1.showHelpTip = !demo1.showHelpTip"
            ></i>
          </vxe-tooltip>
        </template>
      </vxe-column>
      <vxe-column
        title="序号"
        type="seq"
        width="60"
        align="center"
      ></vxe-column>
      <vxe-column field="name" title="姓名" :edit-render="{}" width="150">
        <template #edit="{ row }">
          <vxe-input v-model="row.name" type="text"></vxe-input>
        </template>
      </vxe-column>
      <vxe-column
        field="gender"
        title="性别"
        :edit-render="{}"
        width="100"
        align="center"
      >
        <template #default="{ row }">
          <span>{{ formatSex(row.gender) }}</span>
        </template>
        <template #edit="{ row }">
          <vxe-select
            v-model="row.gender"
            type="text"
            :options="sexList2"
            transfer
          ></vxe-select>
        </template>
      </vxe-column>
      <vxe-column field="age" title="年龄" width="100" align="center">
      </vxe-column>
      <vxe-column
        field="birth"
        title="出生年月"
        :edit-render="{}"
        width="150"
        align="center"
      >
        <template #edit="{ row }">
          <vxe-input
            @change="setDate(row)"
            v-model="row.birth"
            type="date"
            placeholder="请选择日期"
            transfer
          ></vxe-input>
        </template>
      </vxe-column>
      <vxe-column field="address" title="地址" :edit-render="{}" show-overflow>
        <template #edit="{ row }">
          <vxe-input v-model="row.address" type="text"></vxe-input>
        </template>
      </vxe-column>
      <vxe-column title="操作" align="center" width="160">
        <template v-slot="{ row }">
          <vxe-button
            @click="EditUser(row)"
            title="修改地址"
            status="primary"
            icon="vxe-icon-edit"
            size="small"
          ></vxe-button>
          <el-popconfirm
            :title="`确定删除${row.name}吗?`"
            @confirm="deleteUserInfo(row.id)"
          >
            <template #reference>
              <vxe-button
                title="删除用户"
                status="danger"
                icon="vxe-icon-delete-fill"
                size="small"
              ></vxe-button>
            </template>
          </el-popconfirm>
        </template>
      </vxe-column>
    </vxe-table>
    <el-pagination
      style="margin-top: 20px"
      v-model:current-page="page"
      v-model:page-size="limit"
      :page-sizes="[20, 40, 60]"
      :small="false"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="(val: number) => getuserList(1,val)"
      @current-change="(val: number) => getuserList(val,limit)"
    />
  </div>
  <vue3-html2pdf
    :show-layout="false"
    :float-layout="true"
    :enable-download="false"
    :preview-modal="true"
    :paginate-elements-by-height="1800"
    filename="hee hee"
    :pdf-quality="2"
    :manual-pagination="false"
    pdf-format="a4"
    pdf-orientation="landscape"
    pdf-content-width="800px"
    :html-to-pdf-options="htmlToPdfOptions"
    @progress="onProgress($event)"
    @hasStartedGeneration="hasStartedGeneration()"
    @hasGenerated="hasGenerated($event)"
    ref="html2Pdf"
  >
    <template v-slot:pdf-content>
      <vxe-table
        border
        :row-config="{ useKey: true }"
        :scroll-y="{ enabled: false }"
        :data="demo1.tableData"
        :column-config="{ resizable: true }"
        :edit-config="{ trigger: 'click', mode: 'row' }"
        @edit-closed="Editconfig"
      >
        >
        <vxe-column title="序号" type="seq" width="60"></vxe-column>
        <vxe-column field="name" title="姓名" :edit-render="{}" width="100">
          <template #edit="{ row }">
            <vxe-input v-model="row.name" type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="gender" title="性别" :edit-render="{}" width="60">
          <template #default="{ row }">
            <span>{{ formatSex(row.gender) }}</span>
          </template>
          <template #edit="{ row }">
            <vxe-select
              v-model="row.gender"
              type="text"
              :options="sexList2"
              transfer
            ></vxe-select>
          </template>
        </vxe-column>
        <vxe-column field="age" title="年龄" width="60"> </vxe-column>
        <vxe-column
          field="birth"
          title="出生年月"
          :edit-render="{}"
          width="100"
        >
          <template #edit="{ row }">
            <vxe-input
              @change="setDate(row)"
              v-model="row.birth"
              type="date"
              placeholder="请选择日期"
              transfer
            ></vxe-input>
          </template>
        </vxe-column>
        <vxe-column
          field="address"
          title="地址"
          :edit-render="{}"
          show-overflow
        >
          <template #edit="{ row }">
            <vxe-input v-model="row.address" type="text"></vxe-input>
          </template>
        </vxe-column>
      </vxe-table>
    </template>
  </vue3-html2pdf>
</template>
<script setup lang="ts">
import { ElMessage } from "element-plus";
import {
  onMounted,
  reactive,
  ref,
  onUnmounted,
  nextTick,
  getCurrentInstance,
} from "vue";
import { VxeTableInstance } from "vxe-table";
import Sortable from "sortablejs";
import {
  getUserInfoListApi,
  EditUserInfoListApi,
  deleteUserInfoListApi,
} from "@/api/mock/userInfo";
import { usersItemModel } from "@/types";
import { ShowStatus } from "../types";
const xTable1 = ref({} as VxeTableInstance);
const htmlToPdfOptions = {
  margin: 0,
};
const demo1 = reactive({
  showHelpTip: false,
  tableData: [],
});
//总条数
const total = ref<number>(0);
const page = ref<number>(1);
const limit = ref<number>(10);
//性别选项
const sexList2 = ref([
  { label: "", value: "" },
  { label: "男", value: "1" },
  { label: "女", value: "0" },
]);
// 定义事件
const emits = defineEmits(["setShowStatus", "setUserId"]);
//修改地址
const EditUser = (e: any) => {
  emits("setShowStatus", ShowStatus.USER_DETAIL);

  emits("setUserId", e);
};
//添加用户
const showUserAdd = () => {
  emits("setShowStatus", ShowStatus.USER_FORM);
};
//修改用户
const Editconfig = async (e: { row: usersItemModel }) => {
  await EditUserInfoListApi(e.row.id, e.row);
  getuserList(page.value, limit.value);
};
//更改出生年月
const setDate = (e: any) => {
  const today = new Date(); // 获取当前时间的 Date 对象
  e.age = today.getFullYear() - new Date(e.birth).getFullYear();
};
//性别判断
const formatSex = (value: string) => {
  if (value === "1") {
    return "男";
  }
  if (value === "0") {
    return "女";
  }
  return "";
};
let sortable1: any;
//拖拽排序代码
const rowDrop = () => {
  const $table = xTable1.value;
  sortable1 = Sortable.create(
    $table.$el.querySelector(".body--wrapper>.vxe-table--body tbody"),
    {
      handle: ".drag-btn",
      onEnd: (sortableEvent: { newIndex: number; oldIndex: number }) => {
        const newArr = demo1.tableData;
        const newIndex = sortableEvent.newIndex as number;
        const oldIndex = sortableEvent.oldIndex as number;
        const currRow = demo1.tableData.splice(oldIndex, 1)[0];
        newArr.splice(newIndex, 0, currRow);
        const Newsort = newArr[newIndex].sort;
        delete newArr[newIndex]._X_ROW_KEY;
        delete newArr[oldIndex]._X_ROW_KEY;
        newArr[newIndex].sort = newArr[oldIndex].sort;
        newArr[oldIndex].sort = Newsort;
        EditUserInfoListApi(newArr[newIndex].id, newArr[newIndex]);
        EditUserInfoListApi(newArr[oldIndex].id, newArr[oldIndex]);
        demo1.tableData = [];
        nextTick(() => {
          demo1.tableData = newArr;
          getuserList(1, 10);
        });
      },
    }
  );
};
//获取用户列表
const getuserList = async (currentPage: number, pageSize: number) => {
  const res = await getUserInfoListApi(currentPage, pageSize);
  demo1.tableData = res.data;
  total.value = +res.headers["x-total-count"];
};
//删除用户
const deleteUserInfo = async (id: string) => {
  await deleteUserInfoListApi(id);
  ElMessage.success("删除成功");
  getuserList(1, 10);
};
let initTime: any;
nextTick(() => {
  // 加载完成之后在绑定拖动事件
  initTime = setTimeout(() => {
    rowDrop();
  }, 500);
});
onMounted(async () => {
  getuserList(1, limit.value);
}),
  onUnmounted(() => {
    clearTimeout(initTime);
    if (sortable1) {
      sortable1.destroy();
    }
  });
const { proxy } = getCurrentInstance();
const Progressbars = ref(false);
const generateReport = () => {
  proxy.$refs.html2Pdf.generatePdf();
};
const onProgress = (e) => {
  if (!Progressbars.value) {
    NProgress.start();
    Progressbars.value = true;
  } else {
    NProgress.done();
    Progressbars.value = false;
  }
};
</script>
<script lang="ts">
import Vue3Html2pdf from "vue3-html2pdf";
import NProgress from "nprogress"; // 引入nprogress插件
export default {
  components: {
    Vue3Html2pdf,
  },
};
</script>
<style lang=""></style>
